package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@Slf4j
@Api("用户端菜品相关接口")
@RequestMapping("/user/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @ApiOperation( "根据分类id查询菜品" )
    @GetMapping("/list")
    public Result<List<DishVO>> getByCategoryId(Long categoryId) {
        //缓存菜品，加入缓存中有对
         log.info( "根据分类id查询菜品：{}",categoryId );
        // 应菜品数据就直接返回数据，假如没有就执行sql语句并加入到对应缓存中
        //判断缓存中是否有数据
        String key = "dish_"+categoryId;
        List<DishVO> list = (List<DishVO>)redisTemplate.opsForValue().get( key );
        if(list != null && list.size()>0) {
            return Result.success(list);
        }
        //将数据存入缓存，返回sql语句后的结果
        Dish dish = Dish.builder().categoryId( categoryId ).status( StatusConstant.ENABLE ).build();
        list = dishService.getByCategoryIdWithFlavor(dish);
        redisTemplate.opsForValue().set( key,list );
        return Result.success(list);
    }

}
